import 'package:flutter/material.dart';
import 'package:get/get.dart';

import 'recording_state.dart';
import 'sort_filter_dialog.dart';

class RecordingLogic extends GetxController {
  final RecordingState state = RecordingState();
  final TextEditingController contactController = TextEditingController();

  @override
  void onInit() {
    super.onInit();
    // 初始化音频列表数据
    loadAudioList();
  }

  // 加载音频列表
  void loadAudioList() {
    // 这里可以调用API获取音频列表
    // 模拟数据
    state.audioList.addAll([
      {'id': 1, 'title': '转写成功提取的标题', 'date': '2025/3/10', 'time': '17:00', 'duration': '28:11'},
      {'id': 2, 'title': '转写成功提取的标题', 'date': '2025/3/9', 'time': '15:30', 'duration': '15:45'},
    ]);
  }

  // 显示排序和筛选弹窗
  void showSortFilterDialog() {
    Get.bottomSheet(
      SortFilterDialog(
        initialSortType: state.currentSortType.value,
        initialFilterType: state.currentFilterType.value,
        onApply: (sortType, filterType) {
          if (sortType != null) {
            state.currentSortType.value = sortType;
          }
          if (filterType != null) {
            state.currentFilterType.value = filterType;
          }
          // 应用排序和筛选
          applySortAndFilter();
        },
      ),
      isScrollControlled: true,
      backgroundColor: Colors.transparent,
    );
  }

  // 应用排序和筛选
  void applySortAndFilter() {
    // 先备份原始列表
    final List<dynamic> originalList = [...state.audioList];
    
    // 应用排序
    if (state.currentSortType.value == SortType.byTime) {
      originalList.sort((a, b) => '${a['date']} ${a['time']}'.compareTo('${b['date']} ${b['time']}'));
    } else if (state.currentSortType.value == SortType.byDuration) {
      originalList.sort((a, b) => a['duration'].compareTo(b['duration']));
    }
    
    // 应用筛选
    List<dynamic> filteredList = originalList;
    if (state.currentFilterType.value != null) {
      // 根据不同的筛选类型进行筛选
      // 这里需要根据实际数据结构进行调整
      switch (state.currentFilterType.value) {
        case FilterType.showFavorites:
          filteredList = originalList.where((item) => item['isFavorite'] == true).toList();
          break;
        case FilterType.showAdminVisible:
          filteredList = originalList.where((item) => item['visibility'] == 'admin').toList();
          break;
        case FilterType.showAllMembersVisible:
          filteredList = originalList.where((item) => item['visibility'] == 'all').toList();
          break;
        case FilterType.showSelectedMembersVisible:
          filteredList = originalList.where((item) => item['visibility'] == 'selected').toList();
          break;
        default:
          break;
      }
    }
    
    // 更新列表
    state.audioList.clear();
    state.audioList.addAll(filteredList);
  }
}
